<template>
  <el-card class="box-card">
    <!-- 1.0 标题 -->
    <template #header>
      <h2>商品列表</h2>
    </template>
    <!-- 2.0 内容 -->
    <div>
      <el-table :data="tableData" style="width: 100%" fixed>
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <ul>
              <li>
                <span>商品ID</span>
                <p>{{ row.id }}</p>
              </li>
              <li>
                <span>商品名称</span>
                <p>{{ row.name }}</p>
              </li>
              <li>
                <span>所属分类</span>
                <p>{{ row.category }}</p>
              </li>
              <li>
                <span>商品价格</span>
                <p>{{ row.price }}</p>
              </li>
              <li>
                <span>创建时间</span>
                <p>{{ row.ctime | imgurl }}</p>
              </li>
              <li>
                <span>商品销量</span>
                <p>{{ row.sellCount }}</p>
              </li>
              <li>
                <span>商品评价</span>
                <p>{{ row.rating }}</p>
              </li>
              <li>
                <span>商品描述</span>
                <p>{{ row.goodsDesc }}</p>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name"> </el-table-column>
        <el-table-column label="所属分类" prop="category"> </el-table-column>
        <el-table-column label="商品价格" prop="price"> </el-table-column>
        <el-table-column label="商品图片">
          <template v-slot="{ row }">
            <img
              :src="'http://127.0.0.1:5000/upload/imgs/goods_img/' + row.imgUrl"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column label="商品描述" prop="goodsDesc" width="200">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template v-slot="{ row }">
            <el-button type="primary" size="mini" @click="bianji(row)">
              编辑</el-button
            >
            <el-button size="mini" type="danger" @click="delshow(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[1, 3, 5, 10]"
      :page-size="pageSizes"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 弹出面板 -->
    <el-dialog title="商品编辑" :visible.sync="dialogVisible" width="50%">
      <div>
        <!--   {{ main }} -->
        <el-form
          :model="main"
          status-icon
          :rules="rules"
          ref="form"
          label-width="100px"
          class="demo-ruleForm"
          size="mini"
        >
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="main.name"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="cate">
            <el-select v-model="main.cate" placeholder="请选择">
              <el-option
                v-for="item in allc"
                :key="item.cateName"
                :label="item.cateName"
                :value="item.cateName"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <el-input-number
              v-model="main.price"
              :min="1"
              :max="100"
              label="描述文字"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:5000/goods/goods_img_upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品描述" prop="desc">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="main.desc"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="que()">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import moment from 'moment'
import { showlist, delshop, categories, goodsedit } from '../../api/shop.js'
import _ from 'lodash'
export default {
  data() {
    return {
      currentPage: 1,
      pageSizes: 5,
      total: 0,
      tableData: [],
      dialogVisible: false,
      // 双向数据绑定
      main: {
        name: '',
        cate: '',
        price: 0,
        desc: ''
      },
      // 规则
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        cate: [
          { required: true, message: '请选择分类名称', trigger: 'change' }
        ],
        price: [{ required: true, message: '请确定价格', trigger: 'change' }],
        desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      },
      imageUrl: '',
      allc: [],
      pin: 'http://127.0.0.1:5000/upload/imgs/goods_img/'
    }
  },
  created() {
    this.list()
    this.allcate()
  },
  methods: {
    // 获得所有的是商品分类
    async allcate() {
      const data = await categories()
      // console.log(data)
      this.allc = data.categories
    },
    // 渲染列表
    async list() {
      const data = await showlist({
        currentPage: this.currentPage,
        pageSize: this.pageSizes
      })
      // console.log(data)
      this.total = data.total
      this.tableData = data.data
    },
    // 分页效果
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSizes = val
      this.list()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.list()
    },
    // 编辑
    async bianji(obj) {
      this.main = _.cloneDeep(obj)
      this.dialogVisible = true
    },
    // 删除
    delshow(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const data = await delshop({ id })
          if (data.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.list()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = this.pin + res.imgUrl
      this.main.imgUrl = res.imgUrl
    },
    // 图片的格式的规则
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const arr = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      // 判断当前图片的type类型是否在上面的数组中
      // arr.includes(file.type)
      const isJPG = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async que() {
      const data = await goodsedit({
        name: this.main.name,
        category: this.main.category,
        price: this.main.price,
        imgUrl: this.main.imgUrl,
        goodsDesc: this.main.goodsDesc,
        id: this.main.id
      })
      // console.log(data)
      if (data.code === 0) {
        this.$message({
          type: 'success',
          message: data.msg
        })
        this.dialogVisible = false
        this.list()
      } else {
        this.$message.error('不好意思，错了哦')
      }
    }
  },
  // 过滤器img
  filters: {
    imgurl(str) {
      return moment(str).format('YYYY-MM-DD  HH-mm-ss')
    }
  }
}
</script>

<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
img {
  width: 60%;
}
ul {
  width: 700px;
  display: flex;
  flex-wrap: wrap;

  li {
    width: 50%;
    display: flex;
    margin-bottom: 10px;

    span {
      width: 100px;
    }
  }
}
.el-input,
.el-select {
  width: 193px;
}
/deep/ .el-textarea {
  width: 193px;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
